#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :文件夹切割.py
# @Time      :2024/3/27 
# @Author    :CL
# @email     :1037654919@qq.com
import os
import shutil


def get_folder_size(folder):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename)
            total_size += os.path.getsize(filepath)
    return total_size


def split_files_into_folders(input_folder):
    folders = [f for f in os.listdir(input_folder) if os.path.isdir(os.path.join(input_folder, f))]

    for folder_name in folders:
        print(f"Processing folder: {folder_name}")
        folder_path = os.path.join(input_folder, folder_name)
        files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
        total_size = sum(os.path.getsize(os.path.join(folder_path, f)) for f in files)

        if total_size <= 1e9:  # Check if total size is less than 1GB
            continue

        new_folder_count = 1
        current_folder_size = 0
        new_folder_name = f"{folder_name}_{new_folder_count}"
        os.makedirs(os.path.join(input_folder, new_folder_name))

        for file in files:
            if file.endswith(".json"):
                img_name = file.replace(".json", "")  # Remove extension to match with image file
                img_file = img_name  # Assuming image file has no extension
                json_file = file
                img_path = os.path.join(folder_path, img_file)
                json_path = os.path.join(folder_path, json_file)
                # 如果没有img_file，删除file 跳过
                if not os.path.exists(img_path):
                    os.remove(os.path.join(folder_path, json_file))
                    continue
                img_size = os.path.getsize(img_path)
                json_size = os.path.getsize(json_path)

                if current_folder_size + img_size + json_size > 1e9:
                    new_folder_count += 1
                    new_folder_name = f"{folder_name}_{new_folder_count}"
                    os.makedirs(os.path.join(input_folder, new_folder_name))
                    current_folder_size = 0

                shutil.move(img_path, os.path.join(input_folder, new_folder_name, img_file))
                shutil.move(json_path, os.path.join(input_folder, new_folder_name, json_file))
                current_folder_size += img_size + json_size
# 将带括号的文件夹内的文件移回原文件夹
def move_files_from_subfolders(input_folder):
    folder_list = [f for f in os.listdir(input_folder) if os.path.isdir(os.path.join(input_folder, f))]
    for folder_name in folder_list:
        if "(" in folder_name and ")" in folder_name:
            print(f"Moving files from {folder_name}")
            original_folder_name = folder_name.split("(")[0].strip()
            subfolder_path = os.path.join(input_folder, folder_name)
            original_folder_path = os.path.join(input_folder, original_folder_name)
            if not os.path.exists(original_folder_path):
                os.makedirs(original_folder_path)

            for root, dirs, files in os.walk(subfolder_path):
                for file in files:
                    src = os.path.join(root, file)
                    dst = os.path.join(original_folder_path, file)
                    shutil.move(src, dst)
            os.rmdir(subfolder_path)
# 删除空的文件夹
def remove_empty_folders(input_folder):
    for root, dirs, files in os.walk(input_folder, topdown=False):
        for folder in dirs:
            folder_path = os.path.join(root, folder)
            try:
                if not os.listdir(folder_path):  # Check if the folder is empty
                    print(f"Removing empty folder: {folder_path}")
                    os.rmdir(folder_path)
            except:
                pass

#  获取文件夹大小
def get_folder_size_gb(folder):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            try:
                filepath = os.path.join(dirpath, filename)
                total_size += os.path.getsize(filepath)
            except Exception as e:
                print(e,f'pass {filename}')

    total_size_gb = total_size / (1024 ** 3)
    return total_size_gb
if __name__ == "__main__":
    input_folder =f'/media/chenglei3/77D014CED257D1411/images/huaban/'

    folder_size_gb = get_folder_size_gb(input_folder)
    print(f"The size of the folder {input_folder} is: {folder_size_gb} GB")
    # remove_empty_folders(input_folder) #删除空文件夹
    # split_files_into_folders(input_folder)
    # move_files_from_subfolders(input_folder)
